/**
 * Created by Administrator on 2016/6/22.
 */
/*
 * Created by Lifei1102 on 2016/6/13.
 */
'use strict';
swan_pc
    .factory('ExcelManage',function($window){
        var uri='data:application/vnd.ms-excel;base64,',
            template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64=function(s){return $window.btoa(unescape(encodeURIComponent(s)));},
            format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];})};
        return {
            tableToExcel:function(tableId,worksheetName){
                var table=$(tableId),
                    ctx={worksheet:worksheetName,table:table.html()},
                    href=uri+base64(format(template,ctx));
                return href;
            }
        };
    })
    .controller('CalendarController',function($scope,Clip,TimeExchange,UserClip,$rootScope,$state,getAllUsers,$q,ExcelManage){
        getAllUsers.query(function(result){
            $scope.users=result;
        })
        $scope.ShowMyselfOrOthers=true;
        $scope.inputClipName="";
        $scope.users=[];
        $scope.changeShowViewToMe=function(){
            $scope.ShowMyselfOrOthers=true;
        }
        $scope.changeShowViewToOther=function(){
            $scope.ShowMyselfOrOthers=false;
        }
        $scope.ClipBookDetailShow=function(id){
            $scope.clipBookedId=id;
            $state.go("clipbookdetail");
        }
        $scope.inputClipName=null;
        $scope.addClip=function(){
            $state.go("addclip");
        }
        $scope.setDirty=function(){
            $rootScope.calendarDirty=true;
        }
        $scope.clipsBookForMe=[];
        $scope.clipsBookByMe=[];
        $scope.predicate = 'id';
        $scope.reverse = true;
        $scope.page = 1;
        $scope.loadClipList=function() {
            $scope.clipsBookForMe=[];
            $scope.clipsBookByMe=[];
            Clip.query({
                    page: $scope.page - 1,
                    size: 500,
                    sort: [$scope.predicate + ',' + ($scope.reverse ? 'asc' : 'desc'), 'id']
                },
                function (result, headers) {
                    $scope.totalItems = headers('X-Total-Count');
                    $scope.clips = result;
                    angular.forEach($scope.clips, function (data, index, array) {
                        if (data.bookerId != null && data.bookerId != "") {
                            $scope.clipsBookForMe.push(data);
                        } else {
                            $scope.clipsBookByMe.push(data);
                        }
                    })
                });
        }
        $scope.friendNameShow=function(id){
            /*var name="";
            angular.forEach($scope.users,function(data,index,array){
                if(data.id==id){
                    var name=data.firstName;
                    return name;
                }
            })*/
            var name="";
            for(var i=0;i<$scope.users.length;i++){
                //console.log($scope.users[i].id+"   "+id);
                if($scope.users[i].id==id){
                    name= $scope.users[i].firstName;
                    return name;
                }
            }
        }
        $scope.ClipDetailShow=function(id){
            $rootScope.presentEventid=id;
            $state.go("clipdetail");
        }
        $scope.TimeShow=function(time){
            if(time==null){
                return "";
            }
            var date=new Date(time);
            var timer=date.toString();
            timer=TimeExchange.StringtoLocalTime(timer);
            //console.log("clipserch "+time + " " + " "+date + " "+ timer);
            return timer;
        };
        $scope.confirmClip=function(id){
            $scope.currentClip=[];
            var def=$q.defer();
            var pro=def.promise;
            Clip.get({clipid:id},function(result){
                $scope.currentClip=result;
                def.resolve()
            },function(result){
                def.reject();
            })
            pro.then(
                function(){
                    $scope.currentClip.status="CONFIRM";
                    Clip.update({}, $scope.currentClip,
                        function (result) {
                            $scope.ClipListHasChanged=0?1:0;
                            $scope.loadClipList();
                            swal("您已接受好友日程安排", $scope.currentClip.name, "success");
                            $state.go("calendarshow");
                        },
                        function (result) {
                            if(result.status=="409"){
                                swal("添加失败", "您当前接受的日程与原有日程时间冲突，请修改后提交", "error");
                            }
                            swal("接受好友日程安排失败",$scope.currentClip.name, "error");
                        })
                }
            )
        }
        $scope.refuseClip=function(id){
            $scope.currentClip=[];
            var def=$q.defer();
            var pro=def.promise;
            Clip.get({clipid:id},function(result){
                $scope.currentClip=result;
                def.resolve()
            },function(result){
                def.reject();
            })
            pro.then(
                function(){
                    $scope.currentClip.status="CANCEL";
                    Clip.update({}, $scope.currentClip,
                        function (result) {
                            $scope.ClipListHasChanged=0?1:0;
                            $scope.loadClipList();
                            swal("您已拒绝好友日程安排", $scope.currentClip.name, "success");
                            $state.go("calendarshow");
                        },
                        function (result) {
                            swal("拒绝好友日程安排失败",$scope.currentClip.name, "error");
                        })
                }
            )
        }
    //Clip Import And Export
    var ClipExcelHead= [
        "actionRemark",
        "address",
        "advanceInfo",
        "bookerId",
        "category",
        "checkList",
        "code",
        "color",
        "createdBy",
        "createdDate",
        "deletedAt",
        "endTime",
        "id",
        "individualTaskId",
        "isDelayed",
        "isFixed",
        "isImportant",
        "isPrincipal",
        "isSecret",
        "lastModifiedBy",
        "lastModifiedDate",
        "level",
        "linkedActivityId",
        "linkedActivityType",
        "name",
        "organizationId",
        "ownerId",
        "previewTime",
        "relatedCompany",
        "relatedContact",
        "relatedOpp",
        "remark",
        "remind",
        "startTime",
        "status",
        "type",
        "type2",
        "who",
    ]
    function datenum(v, date1904) {
        if (date1904) {
            v += 1462;
        }
        var epoch = Date.parse(v);
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
    }
    function sheet_from_array_of_arrays(data) {
        var ws = {};
        var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
        for (var R = 0; R !== data.length; ++R) {
            for (var C = 0; C !== data[R].length; ++C) {
                if (range.s.r > R) {
                    range.s.r = R;
                }
                if (range.s.c > C) {
                    range.s.c = C;
                }
                if (range.e.r < R) {
                    range.e.r = R;
                }
                if (range.e.c < C) {
                    range.e.c = C;
                }
                var cell = {v: data[R][C]};
                if (cell.v === null) {
                    continue;
                }
                var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                if (typeof cell.v === 'number') {
                    cell.t = 'n';
                } else if (typeof cell.v === 'boolean') {
                    cell.t = 'b';
                } else if (cell.v instanceof Date) {
                    cell.t = 'n';
                    cell.z = XLSX.SSF._table[14];
                    cell.v = datenum(cell.v);
                }
                else {
                    cell.t = 's';
                }

                ws[cell_ref] = cell;
            }
        }
        if (range.s.c < 10000000) {
            ws['!ref'] = XLSX.utils.encode_range(range);
        }
        return ws;
    }
    function Workbook() {
        if (!(this instanceof Workbook)) {
            return new Workbook();
        }
        this.SheetNames = [];
        this.Sheets = {};
    }
    $scope.ClipExport=function(){
        var def=$q.defer();
        var pro=def.promise;
        var t=[];
        var f=0;
        Clip.query({
                page: $scope.page - 1,
                size: 500,
                sort: [$scope.predicate + ',' + ($scope.reverse ? 'asc' : 'desc'), 'id']
            },
            function (result, headers) {
                $scope.totalItems = headers('X-Total-Count');
                $scope.clips = result;
                angular.forEach($scope.clips,function(data,index,array){
                    t.push(data);
                })
                def.resolve(t);
            },function(result){
                swal("网络连接错误");
                });
        pro.then(function(t){
            createExcel(t,"日程表.xlsx");
            },function(r){
            swal("导出失败！");
        })
    }
    function getHead(){
        var h=[];
        h=ClipExcelHead;
        return h;
    }
    function getBody(d){
        var k=Object.keys(d);
        var r=[];
        console.log(k);
        for(var i=0;i< k.length;i++){
            r.push(d[k[i]]);
        }
        console.log(r);
        return r;
    }
    function createExcel(data,file_path){
        var head=getHead();
        //console.log("head");
        //console.log(head);
        var body=[];
        for (var x in data){
            //console.log(data[x]);
            body.push(getBody(data[x]));
        }
        //console.log("body");
        //console.log(body);
        var array = [head,].concat(body);
        var wb = new Workbook(), ws = sheet_from_array_of_arrays(array);

        /* add ranges to worksheet */
        // ws['!merges'] = ranges;
        var ws_name = "Sheet";
        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws;
        /* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
        //yinyong
        var wopts = {bookType: 'xlsx', bookSST: true, type: 'binary'};

        var wbout = XLSX.write(wb, wopts);

        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        /* the saveAs call downloads a file on the local machine */
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), file_path)
    }
});